/**
 * 
 */
package com.gopay.bis.manager.bank.ebank;


import java.util.Map;

import javax.annotation.Resource;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.common.util.BisPayCheckUtils;
import com.gopay.common.Result;
import com.gopay.common.constants.bank.BankConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.cmb.ebank.pay.CmbB2cMessage;
import com.gopay.common.domain.bank.cmb.ebank.query.CmbB2cResMessage;
import com.gopay.common.domain.user.mcc.UserMccTransformReq;
import com.gopay.common.domain.user.mcc.UserMccTransformRes;
import com.gopay.common.exception.GopayException;
import com.gopay.common.user.mcc.manager.UserMccTransformManager;
import com.gopay.remote.bank.BankManagerRemoteService;
import com.gopay.remote.bank.businesses.BankService;

/**
 * 招行网站B2cManager层业务对象
 * 
 * @CmbB2cManager.java
 * @author Ryan
 * @2013-10-29 上午11:22:36 www.gopay.com.cn Inc.All rights reserved.
 */
public class CmbB2cManager implements BankManagerRemoteService {

    @Resource(name = "cmbB2cBankServiceClient")
    private BankService cmbB2cBankServiceClient;
    
    @Resource(name = "cmbB2cBankServiceClientHna")
    private BankService cmbB2cBankServiceClientHna;
    
    @Resource(name = "cmbConfig")
    private Map<String, String> cmbConfig;
    
    @Resource(name = "userMccTransformManager")
    private UserMccTransformManager userMccTransformManager;
    
    @Override
    public Object sign(BaseMessage msg) throws GopayException{
        msg.setBankOrderId(msg.getOrderId().substring(2, 4) + msg.getOrderId().substring(8));   
        CmbB2cMessage message = (CmbB2cMessage) msg;
        message.setBranchID(message.getBranchCode());
        String cono = buildMerchantNo(message);
        message.setCoNo(cono);
        message.setBillNo(msg.getBankOrderId());
        message.setAmt(message.getAmount().toString());
        // 支付日期为八位YYYYMMDD
        message.setDate(message.getOrderDate().substring(0, 8));
        // 区分充值/支付交易
        if (message.isSupportCredit()) {
            // 网上支付
            message.setGoodsType("54011600");
        } else {
            // 信用卡还款
            message.setGoodsType("54010306");
        }
        message.setMerchantUrl(message.getPayRuturnUrl());
        UserMccTransformReq req = new UserMccTransformReq();
        req.setCustId(message.getSpecial2());
        req.setBankCode(BankConstants.BANK_LOGO_CMB);
        //二级商户
        UserMccTransformRes res = userMccTransformManager.graspUserMccInfo(req);
        String reserved ="";
        if(res==null){
            //不可随意更改，此条信息在银行有备份，如果修改请联系银行
            if(BankConstants.GOPAY_CHONGZHI_CUSTID.equals(message.getSpecial2())){
                String subCoNo = BankConstants.CMB_GOPAY_CODE+"gopay";
                String subCoName = BankConstants.GOPAY_NAME;
                String subCoTPCode = subCoNo.substring(4, 8);
                String subCoTPName = "国付宝充值";
                reserved = "<SubCoNo>"+subCoNo+"</SubCoNo><SubCoName>"+subCoName+"</SubCoName><SubCoTPCode>"+subCoTPCode+"</SubCoTPCode><SubCoTPName>"+subCoTPName+"</SubCoTPName>";
            }
        }else{
            String subCoNo = ""+res.getProvince()+""+res.getBankMccCode()+""+res.getGopayMccNum()+"gopay";
            reserved = "<SubCoNo>"+subCoNo+"</SubCoNo><SubCoName>"+res.getCorpName()+"</SubCoName><SubCoTPCode>"+res.getBankMccCode()+"</SubCoTPCode><SubCoTPName>"+res.getBankMccDesc()+"</SubCoTPName>";
        }
        message.setReserved(reserved);
       
        // 提交银行地址
        message.setBankUrl(message.getPayUrl());
        // 调用远程接口请求签名数据
        BankLogUtils.printB2CManagerSignSendLog(message);
        buildMessageObj(message);
        String signVal;
        if(message.isHna()){
            signVal = (String) cmbB2cBankServiceClientHna.sign(message);
        }else{
            signVal = (String) cmbB2cBankServiceClient.sign(message);
        }
        message.setMerchantCode(signVal);
        BankLogUtils.printB2CManagerSignReturnLog(message);
        return msg;
    }

    @Override
    public Object verify(BaseMessage msg) throws GopayException {
        // 调用远程接口请求签名数据
        CmbB2cMessage message = (CmbB2cMessage) msg;
        BankLogUtils.printB2CManagerVerifySendLog(message);
        boolean isVerify;
        if(message.isHna()){
            isVerify = (Boolean) cmbB2cBankServiceClientHna.verify(message);
        }else{
            isVerify = (Boolean) cmbB2cBankServiceClient.verify(message);
        }
        BankLogUtils.printB2CManagerVerifyReturnLog(message,isVerify);
        return isVerify;
    }

    @Override
    public Object query(Object obj) throws GopayException {
        CmbB2cMessage message = (CmbB2cMessage) obj;
        message.setBranchID(message.getBranchCode());
        String cono = buildMerchantNo(message);
        message.setCoNo(cono);
        message.setPwd(message.getPrivatePwd());
        if(BisPayCheckUtils.checkExternalOrderID(message.getOrderId())){
             message.setDate(message.getOrderDate().substring(0,8));
             message.setBillNo(message.getBankOrderId());
        }
        CmbB2cResMessage queryResMsg = null;
        BankLogUtils.printB2CManagerQuerySendLog(message, message);
        if(message.isHna()){
            queryResMsg = (CmbB2cResMessage) cmbB2cBankServiceClientHna.query(message);
        }else{
            queryResMsg = (CmbB2cResMessage) cmbB2cBankServiceClient.query(message);
        }
        queryResMsg.setOutStlmCd(BankConstants.BANK_LOGO_CMB);
        BankLogUtils.printB2CManagerQueryReturnLog(queryResMsg);
        return queryResMsg;
    }

    public void buildMessageObj(CmbB2cMessage cmbB2cMessage) {
        // 加签报文信息
        StringBuffer plainStr = new StringBuffer();
        plainStr.append(cmbB2cMessage.getDate()).append("|");
        plainStr.append(cmbB2cMessage.getBranchID()).append("|");
        plainStr.append(cmbB2cMessage.getCoNo()).append("|");
        plainStr.append(cmbB2cMessage.getBillNo()).append("|");
        plainStr.append(cmbB2cMessage.getAmt()).append("|");
        plainStr.append(cmbB2cMessage.getMerchantUrl()).append("|");
        plainStr.append(cmbB2cMessage.getGoodsType()).append("|");
        cmbB2cMessage.setPlainMessage(plainStr.toString());
    }
    
    /**
     * 招行商户号大额小额
     * @param msg
     * @return
     */
    public String buildMerchantNo(CmbB2cMessage msg){
         //默认为大额商户号
//          String cono = msg.getMerID();
        //获取小额商户
//          String MerchantCode = (String) cmbConfig.get("CMB.B2C.SMALL.AMOUNT.MERCHANTCODE");
//          String [] MerchantCodeArray = MerchantCode.split(",");
//          boolean isSmallAmount = false;
//          //该商户如果为小额商户的话设置小额商户号
//          for(int i=0;i<MerchantCodeArray.length;i++){
//              if(MerchantCodeArray[i].equals(msg.getSpecial2())){
//                  isSmallAmount = true;
//                  break;
//              }
//          }
//          if(isSmallAmount){
//              cono = (String) cmbConfig.get("CMB.B2C.CONO.SMALL.AMOUNT");
//          }
        /********都用小额*******/
//          if(msg.isSmallMer()){
//            cono = (String) cmbConfig.get("CMB.B2C.CONO.SMALL.AMOUNT");
//            cono = msg.getMerID2nd();
//          }
        
        return msg.getMerID2nd();
    }

    @Override
    public Object dayend(BaseMessage base) throws GopayException, Exception {
        // TODO Auto-generated method stub
        return null;
    }

	@Override
	public Object refund(BaseMessage base) throws GopayException {
		// TODO Auto-generated method stub
		return null;
	}

}
